package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
)

var addr = flag.String("addr", ":2333", "http service address")

func main() {
	flag.Parse()
	http.Handle("/", http.HandlerFunc(analysiz))
	http.Handle("/search", http.HandlerFunc(analysiz))
	err := http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Fatal("ListenAndServe:", err)
	}
	fmt.Println("Hello World!")
}

func lookingFor(keywords string) interface{} {
	searchKey := fmt.Sprintf(`{"keyword": "%s"}`, keywords)
	var jsonStr = []byte(searchKey)

	targetUrl := "https://app.51xuexiaoyi.com/api/v1/searchQuestion"
	targetToken := "B54fABteOJTqACi2pgl67yioIXBIu9d8IToWsRv88mYQvA7XzpVWpvQddpzE"

	req, err := http.NewRequest("POST", targetUrl, bytes.NewBuffer(jsonStr))
	req.Header.Add("token", targetToken)
	req.Header.Add("platform", "android")
	req.Header.Add("app-version", "1.0.6")
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("device", "AkZGaA8OzEajRe8n3vkRAuivrxtfBXlL8TOEY8vcccrn")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	fmt.Println("response Status", resp.Status)
	fmt.Println("response Headers", resp.Header)
	body, _ := ioutil.ReadAll(resp.Body)
	IndentJson := make(map[string]interface{})
	err = json.Unmarshal(body, &IndentJson)
	return IndentJson["data"]
}

func analysiz(w http.ResponseWriter, r *http.Request) {
	keyword := r.PostFormValue("keywords")
	answer := lookingFor(keyword)
	t := template.Must(template.ParseFiles("templ.html"))
	t.Execute(w, answer)
}
